<template>
  <el-dialog
    v-model="visible"
    title="选择用户"
    width="70%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="selector-container">
      <div class="left-panel">
        <div class="panel-header">
          <span>组织架构</span>
          <el-button 
            size="small" 
            text 
            @click="handleExpandAll"
          >
            {{ isExpandAll ? '收起全部' : '展开全部' }}
          </el-button>
        </div>
        <div class="panel-content">
          <organization-tree
            ref="orgTreeRef"
            :show-checkbox="false"
            :default-expand-all="isExpandAll"
            :show-member-count="true"
            @node-click="handleOrgNodeClick"
          />
        </div>
      </div>
      
      <div class="middle-panel">
        <div class="panel-header">
          <span>组织成员</span>
          <span v-if="currentOrg" class="current-org">{{ currentOrg.orgName }}</span>
        </div>
        <div class="panel-content">
          <el-checkbox
            v-model="includeChildren"
            label="包含子组织"
            style="margin-bottom: 10px"
            @change="loadOrgMembers"
          />
          <el-table
            :data="orgMembers"
            height="400"
            @selection-change="handleMemberSelection"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="nickname" label="姓名" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="titleName" label="头衔" />
            <el-table-column label="状态">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
                  {{ row.status === 1 ? '在职' : '离职' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div class="right-panel">
        <div class="panel-header">
          <span>已选用户 ({{ selectedUsers.length }})</span>
          <el-button 
            size="small" 
            text 
            type="danger"
            @click="clearSelected"
          >
            清空
          </el-button>
        </div>
        <div class="panel-content">
          <el-scrollbar height="450px">
            <div class="selected-user-list">
              <div 
                v-for="user in selectedUsers" 
                :key="user.userId"
                class="selected-user-item"
              >
                <el-avatar :size="32" :src="user.avatar">
                  {{ user.nickname?.charAt(0) }}
                </el-avatar>
                <div class="user-info">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-org">{{ user.orgName }}</div>
                </div>
                <el-button
                  type="danger"
                  :icon="Close"
                  circle
                  size="small"
                  text
                  @click="removeSelectedUser(user)"
                />
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">
        确定 ({{ selectedUsers.length }})
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getOrganizationMembers, getUserIdsByOrgId } from '@/api/organization'
import { getUserById } from '@/api/user'
import OrganizationTree from './OrganizationTree.vue'
import { ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  // 已选中的用户ID列表
  selectedUserIds: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const orgTreeRef = ref(null)
const currentOrg = ref(null)
const orgMembers = ref([])
const selectedUsers = ref([])
const includeChildren = ref(false)
const isExpandAll = ref(true)

// 处理组织节点点击
const handleOrgNodeClick = async (data) => {
  currentOrg.value = data
  await loadOrgMembers()
}

// 加载组织成员
const loadOrgMembers = async () => {
  if (!currentOrg.value) {
    return
  }
  
  try {
    const res = await getOrganizationMembers(currentOrg.value.id)
    if (res.code === 200) {
      orgMembers.value = res.data.filter(member => member.status === 1)
    }
  } catch (error) {
    console.error('加载组织成员失败:', error)
    ElMessage.error('加载组织成员失败')
  }
}

// 处理成员选择
const handleMemberSelection = (selection) => {
  // 合并已选用户，去重
  const newUsers = selection.filter(member => 
    !selectedUsers.value.some(u => u.userId === member.userId)
  )
  selectedUsers.value.push(...newUsers)
}

// 移除已选用户
const removeSelectedUser = (user) => {
  const index = selectedUsers.value.findIndex(u => u.userId === user.userId)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  }
}

// 清空已选
const clearSelected = () => {
  selectedUsers.value = []
}

// 展开/收起全部
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  if (orgTreeRef.value) {
    orgTreeRef.value.refresh()
  }
}

// 确认选择
const handleConfirm = () => {
  const userIds = selectedUsers.value.map(u => u.userId)
  emit('confirm', userIds, selectedUsers.value)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 初始化已选用户
const initSelectedUsers = async () => {
  if (props.selectedUserIds && props.selectedUserIds.length > 0) {
    try {
      const users = await Promise.all(
        props.selectedUserIds.map(id => getUserById(id))
      )
      selectedUsers.value = users.map(res => res.data).filter(u => u)
    } catch (error) {
      console.error('加载已选用户失败:', error)
    }
  }
}

// 暴露方法
defineExpose({
  initSelectedUsers
})
</script>

<style scoped>
.selector-container {
  display: flex;
  gap: 15px;
  height: 500px;
}

.left-panel,
.middle-panel,
.right-panel {
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.left-panel {
  flex: 1;
}

.middle-panel {
  flex: 1.5;
}

.right-panel {
  flex: 1;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
}

.current-org {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.panel-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.selected-user-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selected-user-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  transition: background 0.3s;
}

.selected-user-item:hover {
  background: #e4e7ed;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-org {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

